package com.work.yshop.ui.activity;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.work.yshop.R;
import com.work.yshop.ui.fragment.SellerHomeFragment;
import com.work.yshop.ui.fragment.SellerProfileFragment;

public class SellerHomeActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private BottomNavigationView bottomNavigationView;
    private Fragment currentFragment;
    private SellerHomeFragment sellerHomeFragment;
    private SellerProfileFragment sellerProfileFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seller_home);
        
        // 初始化UI
        initViews();
        
        // 默认选中首页
        bottomNavigationView.setSelectedItemId(R.id.nav_seller_home);
    }
    
    private void initViews() {
        // 初始化底部导航栏
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(this);
        
        // 初始化Fragment
        sellerHomeFragment = SellerHomeFragment.newInstance();
        sellerProfileFragment = SellerProfileFragment.newInstance();
        
        // 默认显示首页Fragment
        switchFragment(sellerHomeFragment);
    }
    
    /**
     * 切换Fragment
     */
    private void switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        
        // 如果当前Fragment为空，则直接添加目标Fragment
        if (currentFragment == null) {
            transaction.add(R.id.fragment_container, targetFragment).commit();
        } else if (currentFragment != targetFragment) {
            // 如果目标Fragment未添加，则先添加
            if (!targetFragment.isAdded()) {
                transaction.hide(currentFragment).add(R.id.fragment_container, targetFragment).commit();
            } else {
                // 如果目标Fragment已添加，则直接显示
                transaction.hide(currentFragment).show(targetFragment).commit();
            }
        }
        
        currentFragment = targetFragment;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        
        if (itemId == R.id.nav_seller_home) {
            switchFragment(sellerHomeFragment);
            return true;
        } else if (itemId == R.id.nav_seller_profile) {
            switchFragment(sellerProfileFragment);
            return true;
        }
        
        return false;
    }
} 